// stores/user.js
import { defineStore } from "pinia";
import api from "@/api";
import { ref } from "vue";

export const useUserStore = defineStore("user", {
  state: () => ({
    userInfo: {
      id: "",
      nickname: "",
      avatar: "",
      account: "",
      name: "",
      phone: "",
      email: "",
      idCard: "",
      description: "",
      sex: "",
      hobby: "",
      job: "",
      roles: [],
    },
    loading: false,
    error: null,
    isInitialized: false,
    token: localStorage.getItem("token"),
  }),

  actions: {
    setToken(newToken) {
      this.token = newToken;
      localStorage.setItem("token", newToken);
    },
    async initialize() {
      try {
        this.loading = true;
        const token = localStorage.getItem("token");
        if (token) {
          await this.fetchUserInfo();
        }
      } catch (error) {
        this.clearUserInfo();
      } finally {
        this.isInitialized = true;
        this.loading = false;
      }
    },
    async fetchUserInfo() {
      try {
        const response = await api.user.getUserInfo();
        console.log("获取用户信息成功:", response);
        const responseData = response.data;
        if (!responseData || typeof responseData !== "object") {
          throw new Error("无效的响应结构");
        }
        const userData = responseData;
        if (!userData?.id || !userData?.account) {
          throw new Error(`用户数据缺失关键字段: ${JSON.stringify(userData)}`);
        }
        // 转换字段命名（可选）
        const formattedData = {
          id: userData.id,
          account: userData.account,
          name: userData.name,
          nickname: userData.nickname,
          avatar:
            "http://localhost:8080" + userData.avatar || "/default-avatar.png",
          phone: userData.phone,
          email: userData.email,
          idCard: userData.idcard,
          description: userData.description,
          sex: userData.sex,
          hobby: userData.hobby,
          job: userData.job,
          roles: userData.roles,
        };
        this.setUserInfo(formattedData);
        this.setToken(localStorage.getItem("token"));
        console.log("用户信息已更新:", formattedData);
      } catch (error) {
        throw error;
      }
    },

    setUserInfo(info) {
      this.userInfo = {
        ...this.userInfo,
        ...info,
      };
      // 持久化存储
      localStorage.setItem("userInfo", JSON.stringify(this.userInfo));
    },
    async clearUserInfo() {
      this.userInfo = {
        nickname: "",
        avatar: "",
        account: "",
        name: "",
        phone: "",
        email: "",
        idCard: "",
        description: "",
        sex: "",
        hobby: "",
        job: "",
        roles: [],
      };
      this.isInitialized = false;
      this.loading = false;
      this.error = null;

      // 清除所有可能的存储位置
      const storageKeys = [
        "userInfo",
        "access_token",
        "refresh_token",
        "vuex", // 如果有使用vuex
      ];
      storageKeys.forEach((key) => {
        localStorage.removeItem(key);
        sessionStorage.removeItem(key);
      });

      // 清除cookie（如果使用）
      document.cookie.split(";").forEach((cookie) => {
        document.cookie = cookie
          .replace(/^ +/, "")
          .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);
      });
    },
  },
  getters: {
    isReady: (state) => state.isInitialized && !state.loading,
    isLoggedIn: (state) => !!state.userInfo?.id,
  },
});
